package com.abstractgames;

import java.util.ArrayList;

public class Physics {
	
	public static int FIELDHEIGHT = 5*Screen.HEIGHT;
	public static int FIELDWIDTH = 5*Screen.WIDTH;
	
	public static int MAXX = (int) FIELDWIDTH/32;
	public static int MAXY = (int) FIELDHEIGHT/32;
	
	public static ArrayList<Atom> atoms = new ArrayList<Atom>();
	public static ArrayList<Cell> cells = new ArrayList<Cell>();
	
	Physics(){
		
		for(int i=0; i<MAXX; i++)
			for(int j=0; j<MAXY; j++)
			{
				Cell cell = new Cell(i,j);
				cells.add(cell);				
			}
	}
	
	public void tick(){
		trystep();
		collisionstep();
	}
	
	public void trystep(){
		for (int i = 0; i < atoms.size(); i++) {
			Atom atom = atoms.get(i);
			switch(atom.O){
			case 0: atom.XF=(atom.X+1)%(MAXX-1);
				break;
			case 1: atom.XF=(atom.X-1+MAXX-1)%(MAXX-1);
				break;
			case 2: atom.YF=(atom.Y+1)%(MAXY-1);
				break;
			case 3: atom.YF=(atom.Y-1+MAXY-1)%(MAXY-1);
				break;
			}
		}
		
		for(int i=0; i<MAXX; i++)
			for(int j=0; j<MAXY; j++){
				cells.get(j+MAXY*i).booked = 0;								
			}
		
		for (int i = 0; i < atoms.size(); i++) {
			Atom atom = atoms.get(i);
			atom.collided = false;
			cells.get(MAXY*atom.X+atom.Y).booked++;
			cells.get(MAXY*atom.XF+atom.YF).booked++;
		}
	}
	
	
	public void collisionstep(){
		for (int i = 0; i < atoms.size(); i++) {
			Atom atom = atoms.get(i);
			if (cells.get(MAXY*atom.XF+atom.YF).booked > 1){
				atom.collided = true;
				atom.XF = atom.X;
				atom.YF = atom.Y;
				switch(atom.O){
				case 0: atom.O = 1;
					break;
				case 1: atom.O = 0;
					break;
				case 2: atom.O = 3;
					break;
				case 3: atom.O = 2;
					break;
				}
			}
			else{   cells.get(atom.X*MAXY+atom.Y).empty();
					atom.X = atom.XF;
					atom.Y = atom.YF;
					cells.get(atom.X*MAXY+atom.Y).getAtom(i);
				}
			}
	}
}
